<template>
    <el-dialog
        v-model="dialogVisible"
        custom-class="label-dialog-box"
        :title="title"
        width="700px"
        :before-close="cancelHandel">
        <section class="dialog-content-box">
            <div v-if="hasConditiion" class="title-box">
                <el-radio-group v-model="dialogData.labelType">
                    <span v-if="dialogData.labelChooseType == 1">
                        <el-radio :label="3">批量打标签</el-radio>
                        <el-tooltip content="若内容本身已有所选标签，则不针对此内容重复打标签">
                            <img class="help_icon" src="@/assets/image/customer/help_icon.png" alt="" />
                        </el-tooltip>
                        <el-radio :label="4">批量移除标签</el-radio>
                        <el-tooltip content="若内容本身没有所选标签，则不针对此内容重复移除标签">
                            <img class="help_icon" src="@/assets/image/customer/help_icon.png" alt="" />
                        </el-tooltip>
                    </span>
                    <span v-else>
                        <el-radio :label="1">满足任意一个标签</el-radio>
                        <el-radio :label="2">同时满足所有标签</el-radio>
                        <el-radio :label="0">无标签</el-radio>
                    </span>
                </el-radio-group>
                <div class="right">
                    <div class="refresh" @click="getListTagFun(true)">
                        <el-icon class="icon"><refresh-right /></el-icon><span>刷新数据</span>
                    </div>
                    <span>标签不存在？</span>
                    <span class="active" @click="toCreate">
                        <span class="fa fa-edit link-btn" @click="toCreatedLink(props.path)">去创建</span>
                    </span>
                </div>
            </div>
            <div class="seach">
                <el-row>
                    <el-col :span="hasConditiion ? 24 : 14">
                        <el-input
                            v-model="dialogData.seachKey"
                            v-debounce="[seachTab]"
                            placeholder="搜索标签组、标签"
                            :prefix-icon="Search"
                    /></el-col>
                    <el-col v-show="!hasConditiion" :span="10" style="text-align: right"
                        ><div class="refresh" @click="getListTagFun(true)">
                            <el-icon class="icon"><refresh-right /></el-icon><span>刷新数据</span>
                        </div>
                        <span>标签不存在？</span>
                        <span class="active" @click="toCreate">
                            <span class="fa fa-edit link-btn" @click="toCreatedLink('')">去创建</span>
                        </span></el-col
                    >
                </el-row>
            </div>
            <template v-if="labelList.length > 0">
                <el-tabs
                    v-if="dialogData.labelType != 0"
                    v-model="dialogData.activeName"
                    type="card"
                    class="label-tabs-box"
                    @tab-change="handleClick">
                    <el-tab-pane
                        v-for="item in labelList"
                        :key="item.id"
                        class="label-list-content"
                        :label="item.name"
                        :name="item.id">
                        <el-scrollbar v-if="item?.list?.length > 0" height="274px" @scroll="pageScroll">
                            <div
                                v-for="itm in item.list"
                                :id="'tab-item-' + item.id"
                                :key="itm.group_id"
                                class="label-list">
                                <div class="title">{{ itm.group_name }}</div>
                                <div class="label-item-box">
                                    <div
                                        v-for="(it, ind) in itm.tags"
                                        :key="ind"
                                        :class="{ active: it.check }"
                                        @click="chooseTag(it)">
                                        {{ it.name }}
                                    </div>
                                </div>
                            </div>
                        </el-scrollbar>
                        <div v-else height="400px">
                            <el-empty image="/static/noData.png" description="暂无数据"></el-empty>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </template>
            <div v-else height="400px">
                <el-empty image="/static/noData.png" description="暂无数据"></el-empty>
            </div>
        </section>
        <template #footer>
            <div class="dialog-footer">
                <div class="footer_desc">
                    <span
                        >已选<span class="span">{{ chooseDataArr.length }}</span
                        >个标签</span
                    >
                    <span v-if="hasConditiion"
                        >，将为客户<span class="span typeName">{{ labelTypeNameArr[dialogData.labelType] }}</span></span
                    >
                </div>
                <div>
                    <el-button plain @click="clearChoose">清空</el-button>
                    <el-button @click="cancelHandel">取消</el-button>
                    <el-button type="primary" @click="submitHandel">保存</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, reactive, ref, watch, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { listGroupType, listTag, listgroupTag, grouplist } from '@/api/customerCenter';
import { listTagNew, groupListTagNew } from '@/api/customer';
import { IsNotEmpty, getSetionId } from '@/utils/utils';
const type = ref(true); //true：数据源为客户标签；false：数据源是客户群标签
const hasConditiion = ref(true); //是否有搜索栏上面的功能
const emit = defineEmits(['save']);
const dialogVisible = ref(false);
const dialogData = ref({});
const labelList = ref([]);
const title = ref('批量标签');
const chooseDataArr = ref<any>([]); //当前选中的标签
const labelTypeNameArr = ref(['无标签', '满足任意一个标签', '同时满足所有标签', '批量打标签', '批量移除标签']);
let nowPageHeight = 0;
let pageParam = { page: 1, page_size: 50 };
let canScroll = true;
let isCreate = false; //当前是否前往创建标签页面了
const props = defineProps({
    path: {
        type: String,
        default: '/customer/tag/manage'
    }
});
const initDataFun = (type: number, tagType?: number) => {
    let labelType = type == 2 ? 1 : 3; //3批量打标签  4删除  1 满足任意一个标签  2 同时满足所有标签  0无标签
    if (typeof tagType === 'number') {
        labelType = tagType;
    }
    dialogData.value = {
        labelChooseType: type == 2 ? 2 : 1, // 1是批量打标签   2 是选择标签
        // labelType: type == 2 ? 1 : 3, //3批量打标签  4删除  1 满足任意一个标签  2 同时满足所有标签  0无标签
        labelType,
        labelTypeName: '',
        seachKey: '',
        activeName: 1 //当前标签页
    };
};

// 获取标签组类别列表
const getListGroupType = () => {
    if (type.value) {
        return new Promise((res, ref) => {
            listGroupType()
                .then((r: any) => {
                    res(r);
                })
                .catch((e: any) => {
                    ref(e);
                });
        });
    } else {
        return new Promise((res, ref) => {
            listgroupTag()
                .then((r: any) => {
                    res(r);
                })
                .catch((e: any) => {
                    ref(e);
                });
        });
    }
};

watch(dialogVisible, async val => {
    if (val) {
        isCreate = false; //初始化
        nowPageHeight = 0;
        pageParam = {
            page: 1,
            page_size: 50
        };
        initDataFun(dialogData.value.labelChooseType, dialogData.value.tagType);
        const groupData = await getListGroupType();
        labelList.value = groupData && groupData.length > 0 ? groupData : [];
        dialogData.value.activeName = labelList.value.length > 0 ? labelList.value[0].id : '';
        getListTagFun();
    }
});

// 获取标签组内的数据
const getListTagFun: any = isSeach => {
    const index = labelList.value.findIndex(it => {
        return it.id == dialogData.value.activeName;
    });
    if (!labelList.value[index].list) {
        labelList.value[index].list = [];
    }
    if (labelList.value[index].list && labelList.value[index].list.length > 0 && !isSeach) {
        return;
    }
    if (!dialogData.value.activeName) {
        return;
    }
    if (type.value) {
        listTag({
            keyword: dialogData.value.seachKey,
            type_list: dialogData.value.activeName,
            page: pageParam.page,
            page_size: pageParam.page_size
        })
            .then((r: any) => {
                r.data.forEach((item: any) => {
                    item.tags.forEach((itm: any) => {
                        const indx = chooseDataArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                    });
                });
                labelList.value[index].list = r.data;
                nextTick(() => {
                    canScroll = true;
                    nowPageHeight =
                        document.querySelector('#tab-item-' + dialogData.value.activeName)?.offsetHeight || 0;
                });
            })
            .catch((e: any) => {
                canScroll = true;
            });
    } else {
        grouplist({
            keyword: dialogData.value.seachKey,
            // type_list: dialogData.value.activeName,
            type_list: [dialogData.value.activeName],
            page: pageParam.page,
            page_size: pageParam.page_size
        })
            .then((r: any) => {
                r.data.forEach((item: any) => {
                    item.tags.forEach((itm: any) => {
                        const indx = chooseDataArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                    });
                });
                labelList.value[index].list = r.data;
                nextTick(() => {
                    canScroll = true;
                    nowPageHeight =
                        document.querySelector('#tab-item-' + dialogData.value.activeName)?.offsetHeight || 0;
                });
            })
            .catch((e: any) => {
                canScroll = true;
            });
    }
};

onMounted(() => {
    document.addEventListener('visibilitychange', function () {
        //浏览器切换事件
        if (document.visibilityState != 'hidden' && isCreate) {
            getListTagFun();
            isCreate = false;
        }
    });
});

const cancelHandel = () => {
    clearChoose();
    dialogVisible.value = false;
};
// 前往创建
const toCreate = () => {
    isCreate = true;
};

// 滚动加载
const pageScroll = (e: any) => {
    if (nowPageHeight - 244 <= e.scrollTop && canScroll) {
        canScroll = false;
        pageParam.page = pageParam.page + 1;
        getListTagFun();
    }
};

// 保存数据
const submitHandel = () => {
    const { labelChooseType, labelType } = dialogData.value;
    const idList = chooseDataArr.value.map(it => {
        return it.id;
    });
    if (dialogData.value.labelType != 0) {
        emit('save', { labelChooseType, labelType, data: chooseDataArr.value, idList });
    } else {
        emit('save', { labelChooseType, labelType, data: [], idList: [] });
    }
    dialogVisible.value = false;
};

// 选择选项卡
const handleClick = () => {
    pageParam = {
        page: 1,
        page_size: 50
    };
    getListTagFun();
};

// 选择标签
const chooseTag = (val: any): void => {
    val.check = !val.check;
    const index = chooseDataArr.value.findIndex((it: any) => {
        return it?.id == val?.id;
    });
    if (index > -1) {
        chooseDataArr.value.splice(index, 1);
    } else {
        chooseDataArr.value.push(val);
    }
};
// 清空选中的标签
const clearChoose = () => {
    chooseDataArr.value.splice(0);
    const keyArr = Object.keys(labelList.value);
    keyArr.forEach((item: string) => {
        if (labelList.value[item].list) {
            labelList.value[item].list.forEach((itm: object) => {
                if (itm.tags && itm.tags.length > 0) {
                    itm.tags.forEach((it: object) => {
                        it.check = false;
                    });
                }
            });
        }
    });
};
const seachTab = async () => {
    const params = { keyword: dialogData.value?.seachKey };
    try {
        const res: any = type.value ? await listTagNew(params) : await groupListTagNew(params);
        const arr: any[] = [];
        res.forEach((item: any) => {
            item.list = type.value ? item.tag_groups : item.group_chat_tag_groups;
            if (IsNotEmpty(item.list)) {
                item.list.forEach((v: any) => {
                    v.group_id = v.type_id;
                    v.group_name = v.name;
                    v.tags = type.value ? v.cust_tag : v.cust_group_tag;
                });
            }
            arr.push(item);
        });
        if (arr.length) dialogData.value.activeName = arr[0].id;

        getSelectLabel(arr); // 回显选中数据
        labelList.value = arr;
    } catch (error) {
        // console.log(error);
    }
};
// 选中回显
const getSelectLabel = (data: any) => {
    if (chooseDataArr.value.length > 0) {
        const arr = getSetionId('id', chooseDataArr.value);
        data.forEach((item: any) => {
            if (item.list.length > 0) {
                item.list.forEach((v: any) => {
                    if (v?.cust_tag.length > 0) {
                        v?.cust_tag.forEach((k: any) => {
                            if (arr.includes(k?.id)) {
                                k.check = true;
                            }
                        });
                    }
                });
            }
        });
    }
};

const toCreatedLink = (url?: any) => {
    window.open(url || '/customer/tag/manage', '_blank');
};

defineExpose({
    title,
    type,
    dialogVisible,
    hasConditiion,
    dialogData,
    chooseDataArr, //回显的标签数据  {id:***,name:***}
    clearChoose
});
</script>

<style lang="scss" scoped>
.dialog-content-box {
    .title-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .help_icon {
            cursor: pointer;
            width: 14px;
            height: 14px;
            position: relative;
            left: -24px;
        }

        .right {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #969696;

            span {
                vertical-align: middle;
            }

            .active {
                color: #ff6b00;
                cursor: pointer;

                a {
                    color: #ff6b00;
                    text-decoration: none;
                }
            }

            .refresh {
                cursor: pointer;
                display: inline-block;
                line-height: 19px;
                margin-right: 10px;

                .icon {
                    vertical-align: middle;
                    font-size: 16px;
                }

                span {
                    vertical-align: middle;
                }
            }

            .refresh:hover {
                color: #0081ff;

                .icon {
                    color: #0081ff;
                }
            }
        }
    }

    .seach {
        margin-bottom: 20px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #969696;

        .el-row {
            display: flex;
            align-items: center;
        }

        span {
            vertical-align: middle;
        }

        .active {
            color: #ff6b00;
            cursor: pointer;

            a {
                color: #ff6b00;
                text-decoration: none;
            }
        }

        .refresh {
            cursor: pointer;
            display: inline-block;
            line-height: 19px;
            margin-right: 10px;

            .icon {
                vertical-align: middle;
                font-size: 16px;
            }

            span {
                vertical-align: middle;
            }

            &:hover {
                color: #0081ff;

                .icon {
                    color: #0081ff;
                }
            }
        }
    }

    .label-list-content {
        border: solid 1px #eaeaea;
        height: 300px;
        box-sizing: border-box;
        overflow-y: scroll;
        padding: 20px 13px;

        .label-list {
            margin-bottom: 14px;

            .title {
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                color: #33302d;
                margin-bottom: 10px;
            }

            .label-item-box {
                div {
                    display: inline-block;
                    vertical-align: middle;
                    margin-right: 16px;
                    background: #fff;
                    border: 1px solid #eaeaea;
                    height: 22px;
                    line-height: 22px;
                    padding: 0 10px;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    color: #969696;
                    cursor: pointer;
                    margin-bottom: 10px;

                    &.active {
                        border: 1px solid #ff6b00;
                        color: #ff6b00;
                    }
                }
            }
        }
    }

    .label-list-content::-webkit-scrollbar {
        display: none;
    }
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>

<style lang="scss">
.label-tabs-box .el-tabs__header {
    margin-bottom: 0;
    border-bottom: 0;
}

.label-tabs-box .el-tabs__item {
    background: #f9f9f9;
    color: #969696;
}

.label-tabs-box .is-active {
    background: white;
    color: #ff6b00;
}
</style>
